package com.company.woye.checkmakesure;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.company.woye.MyApplication;
import com.company.woye.R;
import com.company.woye.base.BaseActivity;
import com.company.woye.checkmakesure.adapter.MakeSureDeLvBottomAdapter;
import com.company.woye.checkmakesure.adapter.MakeSureDeLvTopAdapter;
import com.company.woye.checkmakesure.bean.LuBuDetailBean;
import com.company.woye.checkmakesure.bean.MakeSureBean;
import com.company.woye.checkmakesure.bean.SuccessBean;
import com.company.woye.internet.KjjPHCallBack;
import com.company.woye.utils.Constans;
import com.company.woye.utils.DBUtil;
import com.company.woye.utils.Toaster;
import com.zhy.http.okhttp.OkHttpUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.MediaType;

import static com.company.woye.MyApplication.UrlCut;

public class MakeSureDetailActivity extends BaseActivity {


    @BindView(R.id.iv_on_package_back)
    ImageView ivOnPackageBack;
    @BindView(R.id.tv_on_package_back)
    TextView tvOnPackageBack;
    @BindView(R.id.tv_sure)
    TextView tvSure;
    @BindView(R.id.tv_on_package_sure)
    TextView tvOnPackageSure;
    @BindView(R.id.tv_on_package_search)
    TextView tvOnPackageSearch;
    @BindView(R.id.tv_look_process)
    TextView tvLookProcess;
    @BindView(R.id.tv_labuzu)
    TextView tvLabuzu;
    @BindView(R.id.tv_hyh)
    TextView tvHyh;
    @BindView(R.id.tv_mkbl)
    TextView tvMkbl;
    @BindView(R.id.tv_jyz)
    TextView tvJyz;
    @BindView(R.id.tv_cplx)
    TextView tvCplx;
    @BindView(R.id.tv_jhcc)
    TextView tvJhcc;
    @BindView(R.id.tv_jhcs)
    TextView tvJhcs;
    @BindView(R.id.tv_dc)
    TextView tvDc;
    @BindView(R.id.tv_sc)
    TextView tvSc;
    @BindView(R.id.tv_ccxh)
    TextView tvCcxh;
    @BindView(R.id.tv_sjcs)
    TextView tvSjcs;
    @BindView(R.id.tv_gmxx)
    TextView tvGmxx;
    @BindView(R.id.tv_code)
    TextView tvCode;
    @BindView(R.id.tv_all_piece)
    TextView tvAllPiece;
    @BindView(R.id.ll)
    LinearLayout ll;
    @BindView(R.id.tv_num)
    TextView tvNum;
    @BindView(R.id.tv_ganghao)
    TextView tvGanghao;
    @BindView(R.id.tv_piece)
    TextView tvPiece;
    @BindView(R.id.tv_mldj)
    TextView tvMldj;
    @BindView(R.id.tv_sb1)
    TextView tvSb;
    @BindView(R.id.lv_top)
    ListView lvTop;
    @BindView(R.id.rl)
    RelativeLayout rl;
    @BindView(R.id.tv_look_detail)
    TextView tvLookDetail;
    @BindView(R.id.tv_size)
    TextView tvSize;
    @BindView(R.id.tv_kds)
    TextView tvKds;
    @BindView(R.id.tv_bdjs)
    TextView tvBdjs;
    @BindView(R.id.tv_zps)
    TextView tvZps;
    @BindView(R.id.tv_jhrq)
    TextView tvJhrq;
    @BindView(R.id.tv_sz)
    TextView tvSz;
    @BindView(R.id.tv_gy)
    TextView tvGy;
    @BindView(R.id.ll2)
    LinearLayout ll2;
    @BindView(R.id.lv_bottom)
    ListView lvBottom;
    @BindView(R.id.ll_on_package_summary)
    LinearLayout llOnPackageSummary;
    @BindView(R.id.tv_tecology_info)
    TextView tvTecologyInfo;
    private JSONArray CheckBaseInfoJson, CheckCompleteJson;
    private final int MSG_CheckBaseInfo = 9001;
    private final int MSG_CutPAD_CheckComplete = 9003;
    private final int MSG_ERROR = 9007;
    MakeSureBean makeSureBean;
    String bbm = "", cjName = "", bmName = "";
    ArrayList<LuBuDetailBean.DataBean.TxmListBean> cutPAD_checkClothBeans = new ArrayList<>();
    ArrayList<LuBuDetailBean.DataBean.DbhListBean> dbhList = new ArrayList<>();
    MakeSureDeLvTopAdapter CheckClothAdapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public int setLayoutId() {
        return R.layout.activity_make_sure_detail;
    }

    @Override
    public void initView() {

        Intent intent = getIntent();
        if (intent != null) {
            cjName = intent.getStringExtra("cjName");
            bmName = intent.getStringExtra("bmName");
            if (!TextUtils.isEmpty(bmName) && bmName.length() > 4) {
                bbm = bmName.substring(0, 4);
            }
            makeSureBean = (MakeSureBean) intent.getSerializableExtra("data");
            if (makeSureBean != null) {
                getBaseinfo(makeSureBean, "CheckBaseInfo");
            } else {
                Toaster.showLong(MakeSureDetailActivity.this, "传递信息为空");
            }
        }

        CheckClothAdapter = new MakeSureDeLvTopAdapter(this, cutPAD_checkClothBeans);
        lvTop.setAdapter(CheckClothAdapter);
    }

    private void getBaseinfo(MakeSureBean makeSureBean, String OperType) {
        String sqlFindcJname = "EXEC [CutPAD_CheckGetBaseInfo] @FormNo='" + makeSureBean.getFormNo() + "',@kdcs='" + makeSureBean.getKdcs()
                + "',@lsx='" + makeSureBean.getLsx() + "',@OperType='" + OperType + "',@debug='0'";
        ReadSQLData(sqlFindcJname, "CheckBaseInfo");
    }

    private void getCheckClothInfo(MakeSureBean makeSureBean) {
        JSONObject params = new JSONObject();
        try {
            params.put("bbm", bbm);
            params.put("bmName", bmName);
            params.put("dh", makeSureBean.getFormNo());
            params.put("cc", makeSureBean.getPlanBedNo());
            params.put("ccxh", makeSureBean.getBedNo());
            params.put("cjName", cjName);
            params.put("hyh", makeSureBean.getHyh());
            params.put("kdcs", makeSureBean.getKdcs());
            params.put("lsx", makeSureBean.getLsx());
            params.put("mkbl", makeSureBean.getMarkRate());
            params.put("token", Constans.token);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Log.e("makesure", params.toString());
        OkHttpUtils.postString()
                .url(Constans.IP + "szapi/third/BdMlcj/listCjlbmx")
                .mediaType(MediaType.parse("application/json"))
                .content(params.toString())
                .build().execute(new KjjPHCallBack<LuBuDetailBean>(LuBuDetailBean.class, MakeSureDetailActivity.this, true) {
            @Override
            public void myError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(LuBuDetailBean response, int id) {
                Log.e("1111", response.toString());
                Toaster.showLong(MakeSureDetailActivity.this, response.getMsg());
                if (response.getData() != null) {
                    if (response.getData().getTxmList() != null && response.getData().getTxmList().size() > 0) {
                        cutPAD_checkClothBeans.clear();
                        cutPAD_checkClothBeans.addAll(response.getData().getTxmList());
                        int allPiece = 0, sb = 0;
                        //计算总层数
                        for (int i = 0; i < cutPAD_checkClothBeans.size(); i++) {
                            if (!TextUtils.isEmpty(cutPAD_checkClothBeans.get(i).getSjcs() + "")) {
                                allPiece += cutPAD_checkClothBeans.get(i).getSjcs();
                            }
                            if (!TextUtils.isEmpty(cutPAD_checkClothBeans.get(i).getSb() + "")) {
                                sb += cutPAD_checkClothBeans.get(i).getSb();
                            }
                        }
                        if (sb == 0) {
                            tvSb.setText("0");
                        } else {
                            tvSb.setText(sb + "");
                        }
                        if (allPiece == 0) {
                            tvAllPiece.setText("0");
                        } else {
                            tvAllPiece.setText(allPiece + "");
                        }
                        CheckClothAdapter.notifyDataSetChanged();
                    } else {
                        Toaster.showLong(MakeSureDetailActivity.this, "拉布明细为空");
                    }
                    if (response.getData().getDbhList() != null && response.getData().getDbhList().size() > 0) {
                        dbhList.clear();
                        dbhList = response.getData().getDbhList();
                        if (dbhList != null && dbhList.size() > 0) {
                            tvTecologyInfo.setText("工艺信息:" + dbhList.get(0).getGy());
                            lvBottom.setAdapter(new MakeSureDeLvBottomAdapter(MakeSureDetailActivity.this, dbhList));
                            int allKds = 0, allBdjs = 0, allZps = 0;
                            for (int i = 0; i < dbhList.size(); i++) {
                                if (!TextUtils.isEmpty(dbhList.get(i).getKds() + "")) {
                                    allKds += dbhList.get(i).getKds();

                                }
                                if (!TextUtils.isEmpty(dbhList.get(i).getBdjs() + "")) {
                                    allBdjs += dbhList.get(i).getBdjs();

                                }
                                if (!TextUtils.isEmpty(dbhList.get(i).getZps() + "")) {
                                    allZps += dbhList.get(i).getZps();
                                }
                            }
                            if (allKds == 0) {
                                tvKds.setText("0");
                            } else {
                                tvKds.setText(allKds + "");
                            }
                            if (allBdjs == 0) {
                                tvBdjs.setText("0");
                            } else {
                                tvBdjs.setText(allBdjs + "");
                            }
                            if (allZps == 0) {
                                tvZps.setText("0");
                            } else {
                                tvZps.setText(allZps + "");
                            }
                        }
                    }
                } else {
                    Toaster.showLong(MakeSureDetailActivity.this, "返回信息为空");
                }

            }
        });
    }

    private void copmlteInfo(MakeSureBean makeSureBean) {

        JSONObject params = new JSONObject();
        try {
            params.put("bbm", bbm);
            params.put("bmName", bmName);
            params.put("cjName", cjName);
            params.put("dh", makeSureBean.getFormNo());
            params.put("kdcs", makeSureBean.getKdcs());
            params.put("inputId", MyApplication.curLoginUserNo);
            params.put("inputMan", MyApplication.curLoginUser);
            params.put("token", Constans.token);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        OkHttpUtils.postString()
                .mediaType(MediaType.parse("application/json"))
                .content(params.toString()).url(Constans.IP + "szapi/third/BdMlcj/listCjlbqr").build().execute(new KjjPHCallBack<SuccessBean>(SuccessBean.class, MakeSureDetailActivity.this, true) {
            @Override
            public void myError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(SuccessBean response, int id) {
                Log.e("rsponce", response.toString());
                Toaster.showLong(MakeSureDetailActivity.this, response.getMsg());

            }
        });

//        String sqlFindcJname = "EXEC [CutPAD_CheckComplete] @FormNo='" + makeSureBean.getFormNo() + "',@kdcs='" + makeSureBean.getKdcs()
//                + "',@OperType='CheckComplete',@debug='0'";
//        ReadSQLData(sqlFindcJname, "CheckComplete");
    }

    private void ReadSQLData(String sql, String type) {
        System.out.print("----存储过程:" + sql);
        Runnable run = new Runnable() {
            @Override
            public void run() {
                try {
                    /**
                     * [{"RoleName":"管理员"},{"RoleName":"调度"},{"RoleName":"装框操作"},{"RoleName":"物流运转"},{"RoleName":"试装箱"}]
                     */
                    JSONArray jsonArray = DBUtil.QuerySQL2JSON(UrlCut, sql);
                    System.out.print("----返回结果：" + jsonArray);
                    if (type.equals("CheckBaseInfo")) {
                        CheckBaseInfoJson = jsonArray;
                        //刷新界面;
                        Message msg = new Message();
                        msg.what = MSG_CheckBaseInfo;
                        handler.removeMessages(msg.what);
                        handler.sendMessage(msg);
                        return;
                    }
                    if (type.equals("CheckComplete")) {
                        CheckCompleteJson = jsonArray;
                        //刷新界面;
                        Message msg = new Message();
                        msg.what = MSG_CutPAD_CheckComplete;
                        handler.removeMessages(msg.what);
                        handler.sendMessage(msg);
                        return;
                    }


                } catch (Exception e) {
                    Message msg = new Message();
                    msg.what = MSG_ERROR;
                    handler.removeMessages(msg.what);
                    handler.sendMessage(msg);
                }

            }

        };
        new Thread(run).start();
    }


    Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                //获取部门
                case MSG_CheckBaseInfo:
                    if (CheckBaseInfoJson != null && CheckBaseInfoJson.length() > 0) {
                        try {
                            if (CheckBaseInfoJson.optJSONObject(0).has("lsx"))
                                tvLabuzu.setText(CheckBaseInfoJson.optJSONObject(0).getString("lsx"));
                            if (CheckBaseInfoJson.optJSONObject(0).has("hyh"))
                                tvHyh.setText(CheckBaseInfoJson.optJSONObject(0).getString("hyh"));
                            if (CheckBaseInfoJson.optJSONObject(0).has("MarkRate"))
                                tvMkbl.setText(CheckBaseInfoJson.optJSONObject(0).getString("MarkRate"));
                            if (CheckBaseInfoJson.optJSONObject(0).has("CheckGroup"))
                                tvJyz.setText(CheckBaseInfoJson.optJSONObject(0).getString("CheckGroup"));
                            if (CheckBaseInfoJson.optJSONObject(0).has("cplx"))
                                tvCplx.setText(CheckBaseInfoJson.optJSONObject(0).getString("cplx"));
                            if (CheckBaseInfoJson.optJSONObject(0).has("PlanBedNo"))
                                tvJhcc.setText(CheckBaseInfoJson.optJSONObject(0).getString("PlanBedNo"));
                            if (CheckBaseInfoJson.optJSONObject(0).has("PlanLevel"))
                                tvJhcs.setText((new BigDecimal(CheckBaseInfoJson.optJSONObject(0).getString("PlanLevel")).setScale(1, BigDecimal.ROUND_HALF_UP)) + "");
                            if (CheckBaseInfoJson.optJSONObject(0).has("kdcs"))
                                tvDc.setText(CheckBaseInfoJson.optJSONObject(0).getString("kdcs"));
                            if (CheckBaseInfoJson.optJSONObject(0).has("sc"))
                                tvSc.setText(CheckBaseInfoJson.optJSONObject(0).getString("sc"));
                            if (CheckBaseInfoJson.optJSONObject(0).has("BedNo"))
                                tvCcxh.setText(CheckBaseInfoJson.optJSONObject(0).getString("BedNo"));
                            if (CheckBaseInfoJson.optJSONObject(0).has("RealLevel"))
                                tvSjcs.setText(CheckBaseInfoJson.optJSONObject(0).getString("RealLevel"));
                            if (CheckBaseInfoJson.optJSONObject(0).has("GmInfo"))
                                tvGmxx.setText(CheckBaseInfoJson.optJSONObject(0).getString("GmInfo"));
                            if (CheckBaseInfoJson.optJSONObject(0).has("FormNo"))
                                tvCode.setText(CheckBaseInfoJson.optJSONObject(0).getString("FormNo"));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    getCheckClothInfo(makeSureBean);
                    break;
                case MSG_CutPAD_CheckComplete:
                    if (CheckCompleteJson != null && CheckCompleteJson.length() > 0) {
                        try {
                            if (CheckCompleteJson.getJSONObject(0).has("ResultInfo")) {
                                Toaster.showLong(MakeSureDetailActivity.this, CheckCompleteJson.getJSONObject(0).getString("ResultInfo"));
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    break;
                case MSG_ERROR:
                    Toaster.showLong(MakeSureDetailActivity.this, "连接数据库失败");
                    break;
                default:
                    break;
            }
        }
    };

    @OnClick({R.id.tv_print, R.id.tv_look_detail, R.id.tv_look_process, R.id.iv_on_package_back, R.id.tv_on_package_back, R.id.tv_sure, R.id.tv_on_package_sure, R.id.tv_on_package_search})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_on_package_back:
            case R.id.tv_on_package_back:
                finish();
                break;
            //打印条码
            case R.id.tv_print:
                /**  * 示例:zymis://host_zymis:8123/jysm_dytm?ch=120100820211201342&kdcs=1*/
                String ch=tvCode.getText().toString().trim();
                String kdcs=tvDc.getText().toString().trim();
                String url="zymis://host_zymis:8123/jysm_dytm?ch="+ch+"&kdcs="+kdcs+"";
                Log.e("打印条码",url);
                Intent intent2 = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                startActivity(intent2);
                break;
            //查看拉布单信息
            case R.id.tv_look_detail:
                if (dbhList != null && dbhList.size() > 0) {
                    Intent intent = new Intent(MakeSureDetailActivity.this, MakeDetailDActivity.class);
                    intent.putExtra("data", dbhList);
                    startActivity(intent);
                } else {
                    Toaster.showLong(MakeSureDetailActivity.this, "任务单信息为空");
                }
                break;
            case R.id.tv_on_package_sure:
                if (makeSureBean != null) {
                    copmlteInfo(makeSureBean);
                } else {
                    Toaster.showLong(MakeSureDetailActivity.this, "还未传递拉布信息");
                }
                break;
            //查看工艺
            case R.id.tv_look_process:
                startActivity(new Intent(MakeSureDetailActivity.this, LookProcessActivity.class));
                break;
            case R.id.tv_on_package_search:
                if (makeSureBean != null) {
                    getBaseinfo(makeSureBean, "CheckBaseInfo");
                } else {
                    Toaster.showLong(MakeSureDetailActivity.this, "传递信息为空");
                }
                break;
        }
    }
}
